﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
using SharpShare.Storage;
using SharpShare.Collections;

namespace SharpShare.Afp.Protocol {
    internal static class Extensions {
        public static Path<string> FromAfpPath(this IEnumerable<string> pathComponents) {
            Path<string> path = Path<string>.Empty;

            foreach (string comp in pathComponents) {
                if (string.IsNullOrEmpty(comp)) {
                    path = path.Up;
                } else {
                    path += comp;
                }
            }

            return path;
        }
        public static IStorageItem FindPath(this IAfpSession session, IEnumerable<string> pathComponents, ushort volumeId, uint directoryId, out IAfpVolume volume) {
            volume = session.GetVolume(volumeId);

            if (volume == null) {
                return null;
            }

            IStorageContainer containerNode = null;

            switch (directoryId) {
                case AfpConstants.RootParentNodeId: {
                        if (pathComponents.First().Equals(volume.StorageProvider.Name, StringComparison.OrdinalIgnoreCase)) {
                            return volume.StorageProvider;
                        }

                        return null;
                    }
                case AfpConstants.RootNodeId:
                    containerNode = volume.StorageProvider;
                    break;
                default:
                    containerNode = volume.GetNode(directoryId).DemandContainer();
                    break;
            }

            var item = containerNode.Locate(pathComponents.FromAfpPath());

            return item;
        }
        public static IEnumerable<TEnum> EnumerateFlags<TEnum>(this TEnum enumEnum) where TEnum : struct {
            long value = Convert.ToInt64(enumEnum);
            long current = 1;

            while (current != 0) {
                long thisValue = (value & current);
                current <<= 1;

                object enumValue = Enum.ToObject(typeof(TEnum), thisValue);

                if (System.Enum.IsDefined(typeof(TEnum), enumValue)) {
                    yield return (TEnum)enumValue;
                }
            }
        }

        public static uint ToMacintoshDate(this DateTime date) {
            date = date.ToUniversalTime();
            DateTime baseTime = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            return (uint)(date - baseTime).TotalSeconds;
        }
        public static DateTime FromMacintoshDate(this uint date) {
            DateTime baseTime = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            DateTime time = (baseTime + TimeSpan.FromSeconds(date));

            return time;
        }
    }


}
